// $('.user_img').src="/img/user_log.png";
let isInVideo=false;
let my_room="";//is in chatroom?
let chatting_user="multi_chat_option";//元素id
let user_list={};
let video_list=$('#video_list');
let my_confirm_result=false;
let  mediaStreamTracks=null;
let my_canvas = document.getElementById('pic_drawer');
let video_me=document.getElementById("video_me");
let video_p2p=document.getElementById("video_p2p");
$('#user_name').text(user_name);
const configuration = {//'stun:stun.l.google.com:19302'
    iceServers: [
        {urls: ['stun:tk-turn2.xirsys.com']},
        {
            username: "6_sBJN3tfCPqLF6P3ZrRcfjeuqmyJoFFwf1Q38HuLV7Jz7c9B54I5Ng1KbA1f3N5AAAAAF_pZ6RXQlk5Mg==",
            credential: "546814d4-48ca-11eb-b82c-0242ac140004",
            urls: [
                "turn:tk-turn2.xirsys.com:80?transport=udp",
                "turn:tk-turn2.xirsys.com:3478?transport=udp",
                "turn:tk-turn2.xirsys.com:80?transport=tcp",
                "turn:tk-turn2.xirsys.com:3478?transport=tcp",
                "turns:tk-turn2.xirsys.com:443?transport=tcp",
                "turns:tk-turn2.xirsys.com:5349?transport=tcp"
            ]
        }
    ]
};//webRTC用
let videoFlashInterval;
navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msgetUserMedia;

const PeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
if(!PeerConnection) window.alert('浏览器不支持WebRTC！');
let pcs={};
function createRemoteVideo(id) {
    let remoteVideo=document.getElementById('video_'+id);
    if (remoteVideo) return remoteVideo;
    video_list.append('<li><video autoplay id="video_'+id+'"></video><span>'+user_list[id]+'</span></li>');
    console.log('新建 '+user_list[id]+' 的视频窗口！');
    return remoteVideo=document.getElementById('video_'+id);
}
function addMsgPic(id,name,src) {//显示接收到的图片
    $('#chat_list').append(
        (id==null)?  '<li class="msgright"><p><img class="msg_pic" src="'+src+'"></p><img></li>'
            :'<li class="msgleft"><div id='+id+'><img>'+name+'</div><p><img class="msg_pic" src="'+src+'"></p></li>'
    );
    let scl =$('#chat_list_scroll');
    scl.animate({scrollTop: scl.get(0).scrollHeight},500);
}
function addMsgRecord(id,name,msg) {//显示收到的消息
    let htext=(id==null)? '<li class="msgright"><p>'+msg+'</p><img></li>'
        : '<li class="msgleft"><div class="chatRecd_'+id+'"><img>'+name+'</div> <p>'+msg+'</p></li>';
    $('#chat_list').append(htext);
    let scl =$('#chat_list_scroll');
    scl.animate({scrollTop: scl.get(0).scrollHeight},500);//移动到最新消息
}
function addUserLi(id,name){
    let user_h='<li class="user_li" id="'+id+'">'+'<img/><span>'+name+'</span></li>';
    $('#user_list').append($(user_h));
}
function makeAutoDialog(text,time) {
    $('#auto-dialogBox').dialogBox({//通知，自动关闭
        autoHide:true,time:time,
        title: '通知', content: text,
    });
}
// function videoSender() {
//     my_canvas.getContext("2d").drawImage(video_me,0,0,my_canvas.width,my_canvas.height);
//     iosocket.emit('msg_video',my_canvas.toDataURL("image/jpeg",0.5));
// }

function videoClick(){
    if(isInVideo){
        $('#btn-dialogBox').dialogBox({
            hasClose: true, hasBtn: true,
            cancelValue: '还没聊够',
            confirmValue:'挂断',
            title: '通知',
            content: '你已然进入了视频聊天,是否挂断？',
            confirm: function (){
                if(chatting_user=='multi_chat_option') iosocket.emit('video_multi',{isNew:false});
                else iosocket.emit('chat_p2p',{what:'video',room:my_room,isQuit:true});
                quitOutVideo();
            },
        });
        return;
    }else{
        if(chatting_user=='multi_chat_option')//加入群视频聊天
            $('#btn-dialogBox').dialogBox({//询问一下
                title: '通知', content: "确认加入群视频聊天？",
                hasBtn: true,hasClose:true, confirmValue:'确认',cancelValue: '算了',
                confirm:()=> {iosocket.emit('video_multi', {isNew: true})}
            });
        else
        $('#btn-dialogBox').dialogBox({//询问一下
            hasBtn: true,hasClose:true, confirmValue:'确认',cancelValue: '算了',
            title: '通知', content: "你正在和"+user_list[chatting_user]+"私聊，确认向对方发送视频聊天请求？",
            confirm:function () {
                iosocket.emit('chat_p2p',{what:'video',room:my_room});
            }
        });
    }
}
function picClick() {
    let btc = $(".btn_choose");
    if(btc.css("display")==="none") btc.show();
    else btc.hide();
}
function onInputEvent(key) {
    if (key=='Enter'){
        sendMsg();
    }
}
function sendMsg() {
        let msg = $('#inputMsg').val();
    $('#inputMsg').val('');
    iosocket.emit('msg_to', {data:msg,type:'text',room: my_room});
    addMsgRecord(null,null,msg);
}
function quitPicClick() {
    $(".btn_choose").hide();
    $('#quitPicBt').hide();
    $('#image_file_sel').show();
    video_me.hidden=true;
    if(mediaStreamTracks) mediaStreamTracks.forEach((track)=>{track.stop();});
    mediaStreamTracks=null;
}
function catPicClick() {
    if(mediaStreamTracks||isInVideo){
        my_canvas.getContext("2d").drawImage(video_me,0,0,my_canvas.width,my_canvas.height);
        iosocket.emit('msg_to',{data: my_canvas.toDataURL("image/jpeg",1),type:'img',room:my_room});
        addMsgPic(null,null,my_canvas.toDataURL("image/jpeg",1));
    }else{
        $('#btn-dialogBox').dialogBox({//询问
            hasBtn: true,hasClose:true, confirmValue:'确认',cancelValue: '算了',
            title: '通知', content: "是否打开摄像头，以便于进行照相发送？",
            confirm:function () {
                video_me.hidden=false;
                navigator.getUserMedia({video:true,audio:false},function(stream){
                    video_me.srcObject=stream;
                    mediaStreamTracks=stream.getTracks();
                    if($('#quitPicBt').is(":hidden")){
                        $('#image_file_sel').hide();
                        $('#quitPicBt').show();
                    }
                },function (e) {
                    console.log(e);
                    if(mediaStreamTracks) mediaStreamTracks.forEach((track)=>{track.stop();});
                    mediaStreamTracks=null;
                    alert('打开摄像头失败！');
                });
            }
        });
    }
}

function readFileAsDataURL(file,onload) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = onload;
    reader.onerror = function() {
        console.log('Unable to read ' + file.fileName);
    };
}
document.getElementById('image_file_sel').onchange=function(e){
    console.log('选择文件');
    readFileAsDataURL(this.files[0],function (event) {
        iosocket.emit('msg_to',{data: event.target.result,type:'img',room:my_room});
        addMsgPic(null,null,event.target.result);
    });
    $(".btn_choose").hide();
}
$('#multi_chat_option').click(function () {
    if(chatting_user!='multi_chat_option'){
        $('#btn-dialogBox').dialogBox({//询问一下是否进入私聊
            hasBtn: true,hasClose:true, confirmValue:'确认',cancelValue: '算了',
            title: '通知', content: "你正在和"+user_list[chatting_user]+"私聊，确定退出嘛？",
            confirm:function () {
                iosocket.emit('chat_p2p',{what:'leave_out'});
            }
        });
    }
    // $('#chat_user_name').text($(this).children().eq(1).text());
});
$('#user_list').on('click', 'li', function () {
    if(chatting_user!='multi_chat_option'){//如果正在私聊
        let id=this.id;
        $('#btn-dialogBox').dialogBox({
            title: '通知', content: "你正在和"+user_list[chatting_user]+"私聊呢，是否退出私聊？（退出将在1s后发生请求）",
            hasBtn: true,hasClose:true, confirmValue:'确认',cancelValue: '算了',
            confirm:function () {
                iosocket.emit('chat_p2p',{what:'leave_out'});
                setTimeout(function () {
                    iosocket.emit('chat_p2p', {what:'request',id:id,val:null});
                    console.log('发送私聊请求（可能会被忽略！）');
                    makeAutoDialog('已经向'+user_list[id]+'发送了私聊请求！',1500);
                },1000);
            }
        });
    }else {//没在私聊就直接询问发送请求
        let id=this.id;
        $('#btn-dialogBox').dialogBox({
            title: '通知', content: "确定向"+user_list[id]+"发送私聊请求？",
            hasBtn: true,hasClose:true, confirmValue:'确认',cancelValue: '算了',
            confirm:function () {
                iosocket.emit('chat_p2p', {what: 'request', id: id, val: null});
                console.log('发送私聊请求');
            }
        });

    }
    // $('#chat_user_name').text($(this).children().eq(1).text());
});
//移动变色事件
$('#user_list').on('mouseenter','li',function () {
    if(this.id==chatting_user) return;
    this.style.backgroundColor='#d7dede';
});
$('#user_list').on('mouseout','li',function () {
    if(this.id==chatting_user) return;
    this.style.backgroundColor='white';
});
$('#multi_chat_option').mouseenter(function (e){
    if(this.id==chatting_user) return;
    this.style.backgroundColor='#d7dede';
});
$('#multi_chat_option').mouseleave(function (e){
    if(this.id==chatting_user) return;
    this.style.backgroundColor='white';
});